package com.myapp.mobilesafe.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.SmsMessage;
import android.telephony.TelephonyManager;
import android.util.Log;


import com.android.internal.telephony.ITelephony;
import com.myapp.mobilesafe.db.dao.BlackListDao;

import java.lang.reflect.Method;

public class BlackListService extends Service {
    private InnerSmsReceiver mReceiver;
    private BlackListDao mDao;
    private TelephonyManager mTM;
    private MyListener mListener;
    private MyObserver mObserver;
    @Override
    public void onCreate() {
        super.onCreate();
        mDao = BlackListDao.getInstance(this);
        mReceiver = new InnerSmsReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.provider.Telephony.SMS_RECEIVED");
        filter.setPriority(Integer.MAX_VALUE);
        registerReceiver(mReceiver, filter);
        mTM = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);

        mListener = new MyListener();
        mTM.listen(mListener, PhoneStateListener.LISTEN_CALL_STATE);
    }

    class MyListener extends PhoneStateListener {

        // 电话状态发生变化后
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            super.onCallStateChanged(state, incomingNumber);
            switch (state) {
                case TelephonyManager.CALL_STATE_RINGING:
                    // 电话铃响, 1, 3
                    int mode = mDao.findMode(incomingNumber);
                    if (mode == 1 || mode == 3) {
                        endCall();
                        mObserver = new MyObserver(new Handler(), incomingNumber);
                        getContentResolver().registerContentObserver(
                                Uri.parse("content://call_log/calls"), true,
                                mObserver);
                    }
                    break;
                default:
                    break;
            }

        }
    }

    /**
     * 通过反射机制获得serviceManager
     * 通过aidl进行电话拦截
     */
    private void endCall() {
        Log.i("hahah","@@@蓝接电话@@@");
        try {
            Class clazz = Class.forName("android.os.ServiceManager");
            Method method = clazz.getMethod("getService", String.class);
            IBinder b = (IBinder) method.invoke(null, TELEPHONY_SERVICE);// 静态方法不需要对象,参1是null
            ITelephony service = ITelephony.Stub.asInterface(b);
            service.endCall();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // 内容观察者
    class MyObserver extends ContentObserver {

        private String incomingNumber;

        public MyObserver(Handler handler, String incomingNumber) {
            super(handler);
            this.incomingNumber = incomingNumber;
        }

        // 数据发生变化,就走此构造方法
        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            System.out.println("通话记录发生变化!!!");
            deleteCalllog(incomingNumber);
            // 注销内容观察者
            getContentResolver().unregisterContentObserver(mObserver);
        }

    }

    class InnerSmsReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            Object[] objs = (Object[]) intent.getExtras().get("pdus");
            for (Object obj : objs) {// 超过140字节,会分多条短信发送
                SmsMessage sms = SmsMessage.createFromPdu((byte[]) obj);

                String originatingAddress = sms.getOriginatingAddress();
                String messageBody = sms.getMessageBody();
                System.out.println("短信号码:" + originatingAddress + ";短信内容:"
                        + messageBody);
                if (mDao.find(originatingAddress)) {
                    // 短信2+全部3
                    // 获取拦截模式
                    int mode = mDao.findMode(originatingAddress);
                    if (mode > 1) {
                        abortBroadcast();
                    }
                }
            }
        }
    }
    public void deleteCalllog(String number) {
        getContentResolver().delete(Uri.parse("content://call_log/calls"),
                "number=?", new String[] { number });
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
        mReceiver = null;
        mTM.listen(mListener, PhoneStateListener.LISTEN_NONE);
        mListener = null;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
